<?php

namespace app\api\controller\common;

use app\api\model\common\CoinModel;
use app\api\model\mine\ComputingPowerModel;
use app\common\controller\Api;
use think\Log;

class Bb extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    protected $b = ['BTC', 'BCH', 'LTC', 'ETC', 'ZEC', 'DASH', 'KAS'];

    /**
     * Notes: 获取币种信息
     * User: 浪子膏
     * Date: 2023/10/17 21:20
     * @return mixed
     */
    public function getB()
    {
        $url = 'https://www.antpool.com/auth/v3/index/poolcoins';

        $data = $this->curl_get($url);
        $data = json_decode($data, true);

        if (!empty($data['code']) && $data['code'] == '000000') {

            $item = $data['data']['items'];
            foreach ($item as $value) {
                if (in_array($value['coinType'], $this->b)) {
                    $coinModel = new CoinModel();
                    $coin = $coinModel->where('coin_type', $value['coinType'])->find();
                    if (empty($coin)) {
                        $coin = $coinModel;
                    }
                    $coin->save([
                        'coin_type' => $value['coinType'] ?? '',
                        'coin_price_usd' => $value['coinPriceUsd'] ?? '',
                        'algorithm' => $value['algorithm'] ?? '',
                        'mining_addr_list' => json_encode($value['miningAddrList']) ?? '',
                        'mining_type' => json_encode($value['miningType']) ?? '',
                        'net_hashrate' => $value['netHashrate'] ?? '',
                        'net_hashrate_unit' => $value['netHashrateUnit'] ?? '',
                        'pool_hashrate' => $value['poolHashrate'] ?? '',
                        'network_diff' => $value['networkDiff'] ?? '',
                        'next_diff' => $value['nextDiff'] ?? '',
                        'minimum_payment' => $value['minimumPayment'] ?? '',
                    ]);
                }
            }

            $this->dataOk();
        } else {
            $this->error('没有获取币种信息');
            Log::error('获取币种信息异常:' . $data['msg'] . json_encode($data));
        }
    }

    /**
     * Notes:到期减半时间获取
     * User: 浪子膏
     * Date: 2023/11/8 09:43
     */
    public function countdown()
    {
        $coin_types = CoinModel::column('coin_type');

        foreach ($coin_types as $item) {
            $url = 'https://www.antpool.com/auth/v3/index/coinRewardHalve?coinType=';
            $url .= $item;
            $data = $this->curl_get($url);
            $data = json_decode($data, true);

            if (!empty($data['code']) && $data['code'] == '000000') {
                $info = $data['data'];
                if (!empty($info['cycleEnd'])) {
                    CoinModel::where('coin_type', $item)->update([
                        'cycle_end' => $info['cycleEnd'],
                        'cycle_update' => date('Y-m-d H:i:s'),
                    ]);
                }
            }
        }

        $this->success();
    }

    public function ry()
    {
        $url = 'https://api-prod.poolin.me/api/public/v2/basedata/coins/block_stats';

        $data = $this->curl_get($url);
        $data = json_decode($data, true);
        $time = time();

        foreach ($data['data'] as $key => $item) {
            CoinModel::where('coin_type', $key)->update([
                'per_unit' => $item['rewards_per_unit'],
                'reward_unit' => $item['reward_unit'],
                'per_unit_time' => $time,
            ]);
        }

        $this->dataOk();
    }


    function curl_get($url)
    {

        $header = array(
            'Accept: application/json',
        );
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 120);

        // 超时设置，以毫秒为单位
        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);

        // 设置请求头
        //  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

        //执行命令
        $data = curl_exec($curl);

        // 显示错误信息
        if (curl_error($curl)) {
            print "Error: " . curl_error($curl);
        } else {
            // 打印返回的内容
            curl_close($curl);
            return $data;
        }
    }

    /**
     * Notes: 算力浮动计算
     * User: cyy
     * Date: 2023/12/7 20:44
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function computeRange()
    {
        $computingPowerModel = new ComputingPowerModel();
        if ($computingPowerModel->range()) {
            $this->success('计算成功');
        }

        $this->error('计算失败，请查看日志');

    }
}